package com.lesama.correspondence;

/*
等待唤醒机制：
  void wait()  使当前线程等待
  void notify()   随机唤醒某个等待的线程
  这些方法需要使用锁对象调用
 */

public class CorrespondenceDemo1 {
    public static void main(String[] args) {
        Printer printer = new Printer();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    try {
                        synchronized (Printer.class) {
                            printer.print1();
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    try {
                        synchronized (Printer.class) {
                            printer.print2();
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();
    }
}

class Printer {
    private int flag = 1;
    public void print1() throws InterruptedException {
        if(flag != 1) {
            Printer.class.wait(); // flag不为1，让线程等待
        }
        System.out.print("鸣");
        System.out.print("濑");
        System.out.print("白");
        System.out.println("羽");

        flag = 2; // 线程处理完，通知其他线程
        Printer.class.notify();
    }

    public void print2() throws InterruptedException {
        if(flag != 2) {
            Printer.class.wait();
        }
        System.out.print("空");
        System.out.print("门");
        System.out.println("苍");

        flag = 1;
        Printer.class.notify();
    }
}
